<?php

namespace app\controller;

use app\BaseController;
use app\model\SchoolModel;
use app\model\ShopModel;
use think\facade\Db;
use think\Request;
use app\middleware\Check;
use think\facade\Validate;
use think\response\Json;
use think\validate\ValidateRule;
/**
 * Class School 管理端 学校控制器
 * @package app\controller
 */
class School extends BaseController
{
    protected $middleware = [Check::class];

    /**学校列表
     * @param Request $request
     * @return Json
     */
    public function school_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['limit'] = $request->post('limit');//每页显示数量
        $input['page'] = $request->post('page');//当前页
        $input['operate_id'] = $request->post('operate_id');//运营方id
        // 参数校验
        $validate = Validate::rule([
            'limit' => ValidateRule::isRequire(null, '缺少参数'),
            'page' => ValidateRule::isRequire(null, '缺少参数'),
            'operate_id' => function ($value) {
                return $value === null ? '缺少参数' : true;
            }
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return SchoolModel::list($input, $request->post('token'));
    }

    /** 简单学校列表
     * @param Request $request
     */
    public function simple_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $data = Db::table('eb_school')->field('id,name')->select()->toArray();
        return jsonSuccess('获取成功！', ['data' => $data]);
    }


    /**添加学校
     * @param Request $request
     * @return Json
     */
    public function increase(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['name'] = $request->post('name');//名称
        $input['logo'] = $request->post('logo');//logo
//        $input['delivery'] = $request->post('delivery');//固定配送费
        $input['company'] = $request->post('company');//公司百分比
        $input['operate_id'] = $request->post('operate_id');//运营方id
        $input['type'] = $request->post('type');//运营方id
        // 参数校验
        $validate = Validate::rule([
            'name' => ValidateRule::isRequire(null, '缺少参数'),
            'logo' => ValidateRule::isRequire(null, '缺少参数'),
//            'delivery' => function ($value) {
//                if ($value === null) {
//                    return '缺少参数';
//                } else if ($value >=0 && $value <= 20) {
//                    return true;
//                } else {
//                    return '不合法参数';
//                }
//            },
            'company' => function ($value) {
                return $value === null ? '缺少参数' : true;
            },
            'operate_id' => function ($value) {
                return $value === null ? '缺少参数' : true;
            },
            'type' => function ($value) {
                if (in_array($value,['1','2'], true)) {
                    return true;
                } else {
                    return '非法参数';
                }
            }
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return SchoolModel::increase($input, $request->post('token'));
    }

    /**管理员获取自己管辖的学校列表
     * @param Request $request
     * @return Json
     */
    public function getOwnList(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['limit'] = $request->post('limit');//名称
        $input['page'] = $request->post('page');//logo
        $input['name'] = $request->post('name');//固定配送费
        // 参数校验
        $validate = Validate::rule([
            'limit' => ValidateRule::isRequire(null, '缺少参数'),
            'page' => ValidateRule::isRequire(null, '缺少参数'),
            'name' => function ($value) {
                return $value === null ? '缺少参数' : true;
            }
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return SchoolModel::getOwnList($input, $request->post('token'));
    }

    /**学校允许下单
     * @param Request $request
     * @return Json
     */
    public function changeAllowOrder(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        $input['allow_order'] = $request->post('allow_order');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'allow_order' => ValidateRule::isRequire(null, '缺少参数')
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return SchoolModel::changeAllowOrder($input, $request->post('token'));
    }

    /**学校允许上楼
     * @param Request $request
     * @return Json
     */
    public function changeGoUp(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        $input['is_go_up'] = $request->post('is_go_up');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'is_go_up' => ValidateRule::isRequire(null, '缺少参数')
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return SchoolModel::changeGoUp($input, $request->post('token'));
    }
    /**管理员获取自己管辖的学校划账费用信息
     * @param Request $request
     * @return Json
     */
    public function getDrawInfo(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数')
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return SchoolModel::getDrawInfo($input, $request->post('token'));
    }

    /**管理员编辑自己管辖的学校划账费用信息
     * @param Request $request
     * @return Json
     */
    public function editDraw(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        $input['dor_manager_price'] = $request->post('dor_manager_price');
        $input['box_price'] = $request->post('box_price');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'dor_manager_price' => ValidateRule::isRequire(null, '缺少参数'),
            'box_price' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return SchoolModel::editDraw($input, $request->post('token'));
    }
    /**删除学校
     * @param Request $request
     * @return Json
     */
    public function delete_school(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return SchoolModel::delete($input, $request->post('token'));
    }

    /**获取单个
     * @param Request $request
     * @return Json
     */
    public function school_find(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');//
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数')
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return SchoolModel::getOnly($input, $request->post('token'));

    }

    /**费用设置列表
     * @param Request $request
     * @return Json
     */
    public function deliveryList(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['school_id'] = $request->post('school_id');//
        // 参数校验
        $validate = Validate::rule([
            'school_id' => ValidateRule::isRequire(null, '缺少参数')
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return SchoolModel::deliveryList($input, $request->post('token'));

    }
    /**费用设置
     * @param Request $request
     * @return Json
     */
    public function editDelivery(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');//
        $input['delivery'] = $request->post('delivery');//
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'delivery' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
//        $temp = '';
//        foreach ($input['delivery'] as $k => $v) {
//            if ($v['max'] <= $v['min']) {
//                return jsonFail('最高价不能小于等于最低价，请仔细检查');
//            }
//            if (isset($input['delivery'][$k-1]) && $v['min'] != $input['delivery'][$k-1]['max']) {
//                return jsonFail('数据缺失');
//            }
//            if (isset($input['delivery'][$k+1]) && $v['max'] != $input['delivery'][$k+1]['min']) {
//                return jsonFail('数据缺失');
//            }
//            $temp .= $v['min'] . '-' . $v['max'] . '-' . $v['service'] . '-' . $v['send'] . ',';
//        }
//        $input['delivery'] = trim($temp,',');
            // 逻辑处理
        return SchoolModel::editDelivery($input, $request->post('token'));

    }
    /**编辑保存学校
     * @param Request $request
     * @return Json
     */
    public function school_edit(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');//id
        $input['name'] = $request->post('name');//名称
        $input['logo'] = $request->post('logo');//logo
        $input['delivery'] = $request->post('delivery');//固定配送费
        $input['company'] = $request->post('company');//公司百分比
        $input['operate_id'] = $request->post('operate_id');//运营方id
        $input['type'] = $request->post('type');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'name' => ValidateRule::isRequire(null, '缺少参数'),
            'logo' => ValidateRule::isRequire(null, '缺少参数'),
            'delivery' => function ($value) {
                if ($value === null) {
                    return '缺少参数';
                } else if ($value >=0 && $value <= 20) {
                    return true;
                } else {
                    return '不合法参数';
                }
            },
            'company' => function ($value) {
                return $value === null ? '缺少参数' : true;
            },
            'operate_id' => function ($value) {
                return $value === null ? '缺少参数' : true;
            },
            'type' => function ($value) {
                if (in_array($value,['1','2'], true)) {
                    return true;
                } else {
                    return '非法参数';
                }
            }
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return SchoolModel::edit($input, $request->post('token'));
    }

    //upload_img图片上传
    public function upload_img()
    {
        $mimeType = "jpg,png,JPG,JPEG,PNG,jpeg";
        $files = request()->file();
        try {
//            validate(['image' => 'fileSize:410241024|fileExt:jpg,png,jpeg'])->check($files);
            $savename = [];
            foreach ($files as $file) {
                $rule_size = 10*1048576;
                $size = $file->getSize();
                if ($size > $rule_size) {
                    return jsonFail('文件大于10M，不符合规范');
                }
                $type = explode('/', $file->getMime())[1];
                if (strpos($mimeType, $type) == false) {
                    return jsonFail('文件类型不符合，不符合规范');
                }
                $savename = \think\facade\Filesystem::disk('public')->putFile('', $file);
            }
//            $img = 'http://' . $_SERVER['SERVER_ADDR'] . 'uploads'.$savename;
             $data =  '/api/public/uploads/' . $savename;
            return jsonSuccess('上传成功',$data);
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }

    //删除图片
    public function delete_img(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $imgurl = $request->param('imgurl');//图片路径
        $id = $request->param('id');//编辑时ID
        $value= $request->param('value');//type：3时填写字段名字
        $type = $request->param('type');//1:eb_school  2:eb_goods 3：eb_user
        if (empty($imgurl)) return jsonFail('上传图片路径');
        $ex = '/api/';
        $count = strpos($imgurl, "$ex");
        $strlen = strlen($ex);
        $str = substr_replace($imgurl, "", $count, $strlen);
        $file = ROOT_PATH() . $str;
        if ($id && $type) {//删除数据库
            switch ($type) {
                case 1://1:eb_school  2:eb_goods
                    $res = Db::table('eb_school')->where('id', $id)->update(['logo' => '']);
                    break;
                case 2://2:eb_goods
                    $res = Db::table('eb_goods')->where('id', $id)->update(['pic' => '']);
                    break;
                case 3://2:eb_user
                    $res = Db::table('eb_user')->where('id', $id)->update([$value => '']);
                    break;
                case 4://2:eb_user
                    $res = Db::table('eb_category')->where('id', $id)->update(['pic' => '']);
                    break;
            }
        }
        @unlink($file);
        return jsonSuccess('删除成功！');
    }

    /** 商户审核（列表）
     * @param Request $request
     * @return Json
     */
    public function shop_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['limit'] = $request->post('limit');
        $input['page'] = $request->post('page');
        $input['shop_name'] = $request->post('shop_name');
        $input['school_name'] = $request->post('school_name');
        $input['is_special'] = $request->post('is_special');
        // 参数校验
        $validate = Validate::rule([
            'limit' => ValidateRule::isRequire(null, '缺少参数'),
            'page' => ValidateRule::isRequire(null, '缺少参数'),
            'shop_name' => function ($value) {
                return $value === null ? '缺少参数' : true;
            },
            'school_name' => function ($value) {
                return $value === null ? '缺少参数' : true;
            },
            'is_special' => function ($value) {
                if ($value === null) {
                    return '缺少参数';
                } else if (in_array($value, ['', '1','2'], true)) {
                    return true;
                } else {
                    return '不合法数据';
                }
            },
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return ShopModel::list($input, $request->post('token'));
    }

    /** 商户审核（类型更改）
     * @param Request $request
     * @return Json
     */
    public function changeSpecial(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        $input['is_special'] = $request->post('is_special');
        $input['proportion'] = $request->post('proportion');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'is_special' => function ($value, $all) {
                if ($value === null) {
                    return '缺少参数';
                } else if (in_array($value, ['1','2'], true)) {
                    if ($value == 1 && $all['proportion'] <= 0 || $all['proportion'] >= 100) {
                        return '不合法数据';
                    }
                    return true;
                } else {
                    return '不合法数据';
                }
            },
            'proportion' => ValidateRule::isRequire(null, '缺少参数')
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return ShopModel::changeSpecial($input, $request->post('token'));
    }

    /** 获取绑定的楼栋
     * @param Request $request
     * @return Json
     */
    public function getBindDor(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return ShopModel::getBindDor($input, $request->post('token'));
    }

    /** 商户绑定楼栋
     * @param Request $request
     * @return Json
     */
    public function bindDor(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        $input['chooseDorList'] = $request->post('chooseDorList');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return ShopModel::bindDor($input, $request->post('token'));
    }


    /** 添加商户后台账号
     * @param Request $request
     * @return Json
     */
    public function addAdmin(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        $input['account'] = $request->post('account');//用户名
        $input['pwd'] = $request->post('pwd');//密码
        $input['repwd'] = $request->post('repwd');//repwd
        $input['phone'] = $request->post('phone');//手机号码
        $input['name'] = $request->post('name'); // 名字
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'account' => ValidateRule::isRequire(null, '缺少参数'),
            'pwd' => ValidateRule::isRequire(null, '缺少参数'),
            'repwd' => function ($value, $all) {
                return $value === $all['pwd'] ? true : '两次密码输入不一致';
            },
            'phone' => ValidateRule::isRequire(null, '缺少参数'),
            'name' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return ShopModel::addAdmin($input, $request->post('token'));
    }

    /** 获取商户后台管理员信息
     * @param Request $request
     * @return Json
     */
    public function storeAdminOnly(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return ShopModel::storeAdminOnly($input, $request->post('token'));
    }

    /** 编辑商户后台账号
     * @param Request $request
     * @return Json
     */
    public function editAdmin(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        $input['account'] = $request->post('account');//用户名
        $input['phone'] = $request->post('phone');//手机号码
        $input['name'] = $request->post('name'); // 名字
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'account' => ValidateRule::isRequire(null, '缺少参数'),
            'phone' => ValidateRule::isRequire(null, '缺少参数'),
            'name' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return ShopModel::editAdmin($input, $request->post('token'));
    }

    /** 编辑商户后台密码
     * @param Request $request
     * @return Json
     */
    public function editPwdAdmin(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        $input['pwd'] = $request->post('pwd');
        $input['chkpwd'] = $request->post('chkpwd');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'pwd' => ValidateRule::isRequire(null, '缺少参数'),
            'chkpwd' => function ($value, $all) {
                return $value === $all['pwd'] ? true : '两次密码输入不一致';
            },
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return ShopModel::editPwdAdmin($input, $request->post('token'));
    }

    /** 修改商户管理员状态
     * @param Request $request
     * @return Json
     */
    public function changeAdminStatus(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        $input['status'] = $request->post('status');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'status' => function ($value) {
                if ($value === null) {
                    return '缺少参数';
                } else if (in_array($value, ['0', '1'], true)) {
                    return true;
                } else {
                    return '不合法参数';
                }
            },
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return ShopModel::changeAdminStatus($input, $request->post('token'));
    }
    /** 商户审核（修改状态）
     * @param Request $request
     * @return Json
     */
    public function edit_shop(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $input['id'] = $request->post('id');
        $input['status'] = $request->post('status');//0 未审核 1已审核 2审核未通过 3已禁用
        $input['remark'] = $request->post('remark');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'status' => function ($value) {
                if ($value === null) {
                    return '缺少参数';
                } else if (in_array($value, ['1','2', '0', '3'], true)) {
                    return true;
                } else {
                    return '不合法数据';
                }
            },
            'remark' => function ($value) {
                if ($value === null) {
                    return '缺少参数';
                } else {
                    return true;
                }
            },
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return ShopModel::edit($input, $request->post('token'));
    }

    /** 商户排序修改
     * @author tmx
     * @param Request $request
     * @return Json
     */
    public function shop_sort(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        $admin =Admin_find($token);
        $id = $request->param('id');//商户ID
        $sort = $request->param('sort');//排序
        if (empty($id)) return jsonFail('商户ID不能为空');
        if (empty($sort)) return jsonFail('排序不能为空');
        $res = Db::table('eb_store')->where('id', $id)->update(['sort' => $sort]);
        if ($res) {
            return jsonSuccess('修改成功！');
        } else {
            return jsonFail('请输入与原来不同的值');
        }
    }
}
